#include "home.h"
#include "lcd/lcd.h"
#include "page_ids.h"
#include "stdio.h"
#include "string.h"
#include "utils/display.h"
#include "motor/hw_encoder.h"

static int8_t current_select_mode = 0;


// 绘制首页界面
void home_page_display(void)
{
    // 关闭背光
    LCD_BLK_Clr();

    // 绘制全局背景
    LCD_Fill(0, 0, LCD_W, LCD_H, BLACK);
    // 绘制来源
    disp_x_center(3, 5, BLUE, 16, (unsigned char *)"立创开发板");
    // 绘制标题
    disp_x_center(3 + 16 + 3, 8, BLUE, 16, (unsigned char *)"简易PID入门套件");

    int x = 40;
    int x_offset = 80;
    int y = 65;
    int y_offset = 80;
    // 绘制任务一：PID定速
    disp_string_rect(x, x_offset, y, y_offset, 2, 24, (unsigned char *)"定速", BLUE);
    int x2 = 200;
    int x2_offset = 80;
    int y2 = 65;
    int y2_offset = 80;
    // 绘制任务二：PID定距
    disp_string_rect(x2, x2_offset, y2, y2_offset, 2, 24, (unsigned char *)"定距", BLUE);

    // 根据首页当前选择内容 绘制选择框
    ui_home_page_select(current_select_mode);

    LCD_BLK_Set(); // 打开背光
}

void home_page_handler(PageEvent event, PageParam *param)
{
    PressEvent buttonEvent = param->data.button.buttonEvent;
    uint8_t buttonId = param->data.button.buttonId;
    switch (event)
    {
    case PAGE_EVENT_KEY_PRESS:
        switch (buttonEvent)
        {
        case SINGLE_CLICK:
            switch (buttonId)
            {
            case 2:
            current_select_mode = 0;
                ui_home_page_select(0);
                break;
            case 3:
            current_select_mode = 1;
                ui_home_page_select(1);
                break;
            case 4:
            if(current_select_mode == 0) {
                PageManager_SwitchPage(PAGE_ID_SPEED);
            } else {
                PageManager_SwitchPage(PAGE_ID_DISTANCE);
            }
                break;
            }
            break;
        case LONG_PRESS_START:
            ui_home_page_select(0);
            break;
        case LONG_PRESS_HOLD:
            ui_home_page_select(0);
            break;
        }
        break;
    case PAGE_EVENT_TIMER_EXPIRE:
        break;
    case PAGE_EVENT_DATA_UPDATE:
        break;
    default:
        break;
    }
}

// 根据按键选择绘制首页两个选项的选择框
void ui_home_page_select(int mode)
{
    char select_box_seze = 5;
    switch (mode)
    {
    case 0: // 选择PID定速模式
        disp_select_box(40, 80, 65, 80, 10, select_box_seze, WHITE);
        disp_select_box(200, 80, 65, 80, 10, select_box_seze, BLACK);
        break;
    case 1: // 选择PID定距模式
        disp_select_box(40, 80, 65, 80, 10, select_box_seze, BLACK);
        disp_select_box(200, 80, 65, 80, 10, select_box_seze, WHITE);
        break;
    }
}





PageDescriptor home_page = {
    .pageId = PAGE_ID_HOME,
    .displayFunc = home_page_display,
    .eventHandler = home_page_handler,
};